package cn.itsource.org.service.impl;

import cn.itsource.basic.config.BussinessException;
import cn.itsource.basic.util.BaiduAuditUtils;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.domain.ShopAuditLog;
import cn.itsource.org.enu.ShopStateEum;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.mapper.ShopAuditLogMapper;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.org.service.IShopService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.org.vo.ShopEchartsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itsource
 * @since 2022-10-15
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopAuditLogMapper auditLogMapper;
    @Autowired
    private JavaMailSender sender;

    /**
     * 店铺入驻流程
     * @param shop
     */
    @Override
    public void settlement(Shop shop) {
        Employee admin = shop.getAdmin();
        Employee employee = this.verify(shop, admin);
        // ===============================================
        // 存入数据了
        // 添加shop表
        shopMapper.add(shop);
        if (null == employee){
            // 添加emp
            employee = admin;
            employeeMapper.add(employee);
        }

        // 修改emp的shopId
//        Employee employee1 = new Employee();
//        employee1.setId(employee.getId());
//        employee1.setShopId(shop.getId());
        employee.setShopId(shop.getId());
        employeeMapper.update(employee);
        // 修改shop表的adminId
        Shop uptShop = new Shop();
        uptShop.setId(shop.getId());
        uptShop.setAdminId(employee.getId());
        shopMapper.update(uptShop);

    }

    /**
     * 店铺审核通过接口
     * @param auditLog
     */

    @Override
    public void auditPass(ShopAuditLog auditLog) {
        // 判断参数
        if (StringUtils.isBlank(auditLog.getNote())){
            throw new BussinessException("备注不能为空！");
        }
        // 修改店铺的状态为 审核通过/待激活
        Shop shop = new Shop();
        shop.setId(auditLog.getShopId());
        shop.setState(1);
        shopMapper.update(shop);
        // 添加店铺日志
        // TODO 我们还没做登陆注册 现在手动写死一个 审核人id
        auditLog.setAuditId(123L);
        auditLogMapper.add(auditLog);
        // 发送邮件
        // 1.创建复杂邮件对象
        MimeMessage mimeMessage = sender.createMimeMessage();
        // 2.发送复杂邮件的工具类
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("452627526@qq.com");
            helper.setSubject("宠物之家审核结果通知");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>恭喜您审核您审核通过，点击下方链接激活店铺</h1>"+
                    "http://localhost:8080/shop/active/"+auditLog.getShopId(),true);
            // 5.设置收件人
            helper.setTo("452627526@qq.com");
        } catch (Exception e) {
          throw new BussinessException("发送邮件错误！");
        }
        // 6.发送邮件
        sender.send(mimeMessage);
    }

    @Override
    public void active(Long id) {
        Shop shop = new Shop();
        shop.setId(id);
        shop.setState(2);
        shopMapper.update(shop);
    }

    @Override
    public Map<String, Object> echarts() {
        Map<String,Object> result = new HashMap<>();
        List<ShopEchartsVo> vo= shopMapper.echarts();
        List<Integer> x = vo.stream().map(ShopEchartsVo::getState).collect(Collectors.toList());
//        List<Integer> xT = new ArrayList<>();
//        for (ShopEchartsVo echartsVo : vo) {
//            xT.add(echartsVo.getState());
//        }
        List<Integer> y = vo.stream().map(ShopEchartsVo::getCount).collect(Collectors.toList());
        List<String> realX = new ArrayList<>();
        for (Integer xTemp : x) {
            String stateName = ShopStateEum.getNameByCode(xTemp);
            realX.add(stateName);
        }
        result.put("x",realX);
        result.put("y",y);
        return result;
    }

    private Employee verify(Shop shop, Employee admin) {
        // 校验参数 todo 你们该怎么写就怎么写
        if (StringUtils.isBlank(shop.getName())){
            throw new BussinessException("店铺名称不能为空！");
        }
        // 校验两次密码是否一致

        if (!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BussinessException("两次密码不一致！");
        }
        //  AI验证
        if (!BaiduAuditUtils.TextCensor(shop.getName())){
            throw new BussinessException("店铺名称不合规！");
        }
        if (!BaiduAuditUtils.ImgCensor(shop.getLogo())){
            throw new BussinessException("店铺logo不合规！");
        }
        // 店铺名称是否存在
        Shop tmpShop = shopMapper.findByName(shop.getName());
        if (null != tmpShop){
            throw new BussinessException("店铺已经存在！");
        }
        // 当前管理员是否管理了其他店铺
        Employee employee = employeeMapper.findByName(admin.getUsername());
        if (null != employee && null != employee.getShopId()){
            Shop shopById = shopMapper.findById(employee.getShopId());
            if (shopById.getAdminId().equals(employee.getId())){
                throw new BussinessException("当前管理员已经关联了店铺了！");
            }
        }
        return employee;
    }
}
